package com.helen.exam03.DataCsv;/*
 *@Author: helen
 *@Date:   2021/5/11 11:27
 *@Description:
 */

import com.helen.exam03.Entity.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class CsvData {
    private static RestTemplate restTemplate = new RestTemplate();

    /*
     * @Author   helen
     * @Date     2021/5/11 14:32
     * @Param    爬取数据的url
     * @Return   网址数据的输入流
     * @Descriptions
     */
    public static InputStream readAResource(String url) throws IOException {

        RequestEntity<Void> requestEntity = RequestEntity
                .get(url)
                .headers(httpHeaders -> httpHeaders.add("User-Agent","Mozilla/5.0"))
                .build();

        ResponseEntity<Resource> exchange = restTemplate.exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        return body.getInputStream();
    }

    public static List<RegionStats> handleResource(InputStream input) throws IOException {
        Reader in = new BufferedReader(new InputStreamReader(input));
        List<RegionStats> list = new LinkedList<>();

        Iterable<CSVRecord> records = CSVFormat.DEFAULT
                .withFirstRecordAsHeader() //第一行为Header
                .withRecordSeparator("\n")//行之间分隔符为换行符
                .withDelimiter(',')//列之间分割符为逗号
                .withQuote('"') //忽略双引号之间的逗号
                .parse(in);

        for (CSVRecord record: records) {
            int latestTotalCases = Integer.parseInt(record.get(record.size() - 1));
            int diffFormPrevDay = Integer.parseInt(record.get(record.size() - 1))
                    - Integer.valueOf(record.get(record.size() - 2));
            RegionStats rs = new RegionStats(record.get(0), record.get(1),
                    latestTotalCases, diffFormPrevDay);
            list.add(rs);
        }

        Collections.sort(list);
        return list;
    }


}
